package com.xmy.cultivate.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lkl.laop.sdk.LKLSDK;
import com.lkl.laop.sdk.exception.SDKException;
import com.lkl.laop.sdk.request.V3CcssCounterOrderCloseRequest;
import com.lkl.laop.sdk.request.V3CcssCounterOrderSpecialCreateRequest;
import com.xmy.cultivate.entity.LklOrder;
import com.xmy.cultivate.respons.LklPay;
import com.xmy.cultivate.service.ILklOrderService;
import com.xmy.cultivate.service.ILklPayService;
import com.xmy.cultivate.service.IMqPushService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;

@Service
public class LklPayServiceImpl implements ILklPayService {

    @Autowired
    IMqPushService iMqPushService;

    @Autowired
    ILklOrderService iLklOrderService;

    /**
     * 创建拉卡拉订单
     *
     * @throws SDKException
     */
    public LklPay createOrder(LklPay lklPay) throws SDKException {
        try {
            V3CcssCounterOrderSpecialCreateRequest req = new V3CcssCounterOrderSpecialCreateRequest();
            req.setOutOrderNo(lklPay.getOutOrderNo());//商户订单号
            req.setMerchantNo(lklPay.getMerchantNo());//商户号
            //req.setTermNo("A1160237");
            req.setTotalAmount(lklPay.getTotalAmount());//订单金额，单位：分
            req.setOrderEfficientTime(lklPay.getOrderEfficientTime());//订单有效期 格式yyyyMMddHHmmss,最大支持下单时间+7天
            req.setNotifyUrl(lklPay.getNotifyUrl());//订单支付成功后商户接收订单通知的地址 http://xxx.xxx.com
            req.setSupportRefund(1);//是否支持退款 默认0 不支持
            req.setSupportRepeatPay(1);//是否支持“多次发起支付” 默认0 不支持
            req.setSupportCancel(1);
            //req.setCounterParam("{\"pay_mode\":\"ALIPAY\"}");//支付方式
            req.setCounterRemark("备注");//收银台备注
            //req.setGoodsMark("1");
            //req.setProductId("200809");
            req.setAgeLimit("0");//0:不限年龄；1:年龄限制
            req.setRepeatPayAutoRefund("0");//0:重复支付后不自动退货；1:重复支付后自动退货
            req.setRepeatPayNotify("0");//0:重复支付订单不通知；1:重复支付订单通知 （默认不送为0）
            req.setCloseOrderAutoRefund("0");//0:不自动退货；1:关闭订单后支付成功触发自动退货 （默认不送为0）
            req.setShopName(lklPay.getShopName());//网点名称

//        V3CcssCounterOrderSpecialCreateRequest.TransferField transferField = new V3CcssCounterOrderSpecialCreateRequest.TransferField();
//        transferField.setAccOutName("张三");
//        transferField.setAccOutNo("62266211223334323");
//        transferField.setAdditional("转账附言");
//        req.setTransferField(transferField);
//
//        V3CcssOrderGoodsFieldInfo v3CcssOrderGoodsFieldInfo = new V3CcssOrderGoodsFieldInfo();
//        v3CcssOrderGoodsFieldInfo.setGoodsAmt(100L);
//        v3CcssOrderGoodsFieldInfo.setGoodsNum(1);
//        v3CcssOrderGoodsFieldInfo.setGoodsPricingUnit("1");
//        v3CcssOrderGoodsFieldInfo.setGoodsName("卅");
//        v3CcssOrderGoodsFieldInfo.setTePlatformType("2");
//        v3CcssOrderGoodsFieldInfo.setTePlatformName("amazon");
//        v3CcssOrderGoodsFieldInfo.setGoodsType("11");
//        req.setGoodsField(JsonUtils.toJSONString(v3CcssOrderGoodsFieldInfo));
//
//        req.setSupportCancel(0);
//        req.setBusiTypeParam("[{\"busi_type\":\"UPCARD\",\"params\":{\"crd_flg\":\"CRDFLG_D|CRDFLG_C|CRDFLG_OTH\"}},{\"busi_type\":\"SCPAY\",\"params\":{\"pay_mode\":\"WECHAT\",\"crd_flg\":\"CRDFLG_D\"}}]");
//
//        req.setOrderInfo("测试12313131");
//        req.setSplitMark("0");
//        List<V3CcssOrderOutSplitInfo> outSplitInfos = new ArrayList<>();
//        V3CcssOrderOutSplitInfo outSplitInfo = new V3CcssOrderOutSplitInfo();
//        outSplitInfo.setMerchantNo("82229007392000A");
//        outSplitInfo.setOutSubOrderNo("8221210594300JY20230823151137008");
//        outSplitInfo.setAmount("100");
//        outSplitInfo.setTermNo("T12331234");
//        outSplitInfos.add(outSplitInfo);
//        //req.setOutSplitInfo(outSplitInfos);
//        List<String> sgnInfos = new ArrayList<>();
//        sgnInfos.add("1");
//        req.setSgnInfo(sgnInfos);



            /* 花呗分期场景 **/
//        V3CcssOrderSceneFieldInfo hbFq = new V3CcssOrderSceneFieldInfo();
//        V3CcssOrderSceneFieldInfo.HbFqSceneInfo hbFqSceneInfo = new V3CcssOrderSceneFieldInfo.HbFqSceneInfo();
//        hbFqSceneInfo.setHbFqNum("3");
//        hbFqSceneInfo.setHbFqSellerPercent("0");
//        hbFq.setSceneInfo(JsonUtils.toJSONString(hbFqSceneInfo));
//        hbFq.setOrderSceneType("HB_FQ");
//
//        /* 线上外卡场景  **/
//        V3CcssOrderSceneFieldInfo onlineWild = new V3CcssOrderSceneFieldInfo();
//        onlineWild.setOrderSceneType("ONLINE_WILDCARD");
//        V3CcssOrderSceneFieldInfo.OnlineWildcardSceneInfo onlineWildcardSceneInfo = new V3CcssOrderSceneFieldInfo.OnlineWildcardSceneInfo();
//        onlineWildcardSceneInfo.setUserId("12312312");
//        onlineWildcardSceneInfo.setUserCreateDate("20230402121212");
//        onlineWildcardSceneInfo.setRecipientStreet("Main Street");
//        onlineWildcardSceneInfo.setRecipientCity("New York");
//        onlineWildcardSceneInfo.setRecipientStateOrProvince("BT");
//        onlineWildcardSceneInfo.setRecipientCountry("USA");
//        onlineWild.setSceneInfo(JsonUtils.toJSONString(onlineWildcardSceneInfo));
//
//        V3CcssOrderSceneFieldInfo.OnlineWildcardEncryptedField onlineWildcardEncryptedField = new V3CcssOrderSceneFieldInfo.OnlineWildcardEncryptedField();
//        V3CcssOrderSceneOnlineWildcardBillAddress billAddress = new V3CcssOrderSceneOnlineWildcardBillAddress();
//        billAddress.setHouseNumberOrName("123 Main St");
//        billAddress.setStreet("Main Street");
//        billAddress.setCountry("USA");
//        billAddress.setCity("New York");
//        billAddress.setStateOrProvince("BT");
//        billAddress.setPostalCode("10001");
//        onlineWildcardEncryptedField.setBillingAddress(JsonUtils.toJSONString(billAddress));
//        onlineWildcardEncryptedField.setEmail("123124141@163.com");
//        onlineWildcardEncryptedField.setMobilePhone("+86 13531231231");
//        onlineWildcardEncryptedField.setRecipientFirstName("三");
//        onlineWildcardEncryptedField.setRecipientLastName("张");
//        onlineWild.setEncryptedField(JsonUtils.toJSONString(onlineWildcardEncryptedField));
//
//
//        /* 考拉分期场景  **/
//        V3CcssOrderSceneFieldInfo klfq = new V3CcssOrderSceneFieldInfo();
//        klfq.setOrderSceneType("KL_FQ");
//        V3CcssOrderSceneFieldInfo.KlFqSceneInfo klFqSceneInfo = new V3CcssOrderSceneFieldInfo.KlFqSceneInfo();
//        V3CcssOrderSceneFieldInfo.UnFqInfo unFqInfo = new V3CcssOrderSceneFieldInfo.UnFqInfo();
//        unFqInfo.setIsForce("01");
//        unFqInfo.setUnFqNum("6");
//        unFqInfo.setUnFqSellerPercent("0");
//        klFqSceneInfo.setUnfq(JsonUtils.toJSONString(unFqInfo));
//        V3CcssOrderSceneFieldInfo.HbFqSceneInfo hbFqSceneInfo2 = new V3CcssOrderSceneFieldInfo.HbFqSceneInfo();
//        hbFqSceneInfo2.setHbFqNum("3");
//        hbFqSceneInfo2.setHbFqSellerPercent("0");
//        klFqSceneInfo.setHbfq(JsonUtils.toJSONString(hbFqSceneInfo2));
//
//        klfq.setSceneInfo(JsonUtils.toJSONString(klFqSceneInfo));
//
//        V3CcssOrderSceneFieldInfo.KlFqEncryptedField klFqEncryptedField = new V3CcssOrderSceneFieldInfo.KlFqEncryptedField();
//        V3CcssOrderSceneKlFqUnFqInfo klFqUnFqInfo = new V3CcssOrderSceneKlFqUnFqInfo();
//        klFqUnFqInfo.setCardNo("623622656535665656");
//        klFqUnFqInfo.setBankNm("招商银行");
//        klFqEncryptedField.setUnfq(JsonUtils.toJSONString(klFqUnFqInfo));
//
//        klfq.setEncryptedField(JsonUtils.toJSONString(klFqEncryptedField));
//
//
//        //req.setOrderSceneField(info);
//        req.setOrderSceneField(klfq);

            //System.out.println(JsonUtils.toJSONString(req));

            //3. 发送请求
            String response = LKLSDK.httpPost(req);

            //4. 响应
            //System.out.println(response);

            //5. 解析响应，获取支付链接
            JSONObject jsonObject = JSONObject.parseObject(response);
            System.out.println("解析响应jsonObject："+jsonObject.toString());
            String rsCode =  jsonObject.getString("code");
            if (rsCode.equals("000000")){
                // 获取resp_data对象
                JSONObject respData = jsonObject.getJSONObject("resp_data");
                if (respData != null) {
                    // 获取counter_url的值
                    String counterUrl = respData.getString("counter_url");
                    lklPay.setCounterUrl(counterUrl);
                }

                // 添加到拉卡拉订单表
                LklOrder lklOrder = new LklOrder();
                lklOrder.setOrderEfficientTime(lklPay.getOrderEfficientTime());
                lklOrder.setOrderCreateTime(lklPay.getOrderEfficientTime());
                lklOrder.setMerchantNo(lklPay.getMerchantNo());
                lklOrder.setOutOrderNo(lklPay.getOutOrderNo());
                lklOrder.setTotalAmount(lklPay.getTotalAmount());
                lklOrder.setShopName(lklPay.getShopName());
                lklOrder.setCounterUrl(lklPay.getCounterUrl());
                iLklOrderService.save(lklOrder);
                LocalDateTime nowDateTime = LocalDateTime.now();
                Duration duration = Duration.between(nowDateTime,lklPay.getEfficientDateTime());
                Long secondsStart = duration.getSeconds();//上课相差秒
                if (secondsStart>0){
                    iMqPushService.lklPayExpire(lklPay.getOutOrderNo(),secondsStart);
                }
                lklPay.setPaySeccess(1);
            }else {
                lklPay.setPaySeccess(0);
            }
        }catch (Exception e){
            lklPay.setPaySeccess(0);
        }
        return lklPay;
    }

    /**
     * 关闭订单
     * @param outOrderNo
     * @return
     * @throws SDKException
     */
    @Override
    public boolean closeOrder(String outOrderNo) throws SDKException {
        try {
            QueryWrapper<LklOrder> orderQueryWrapper = new QueryWrapper<>();
            orderQueryWrapper.eq("out_order_no",outOrderNo);
            orderQueryWrapper.last("limit 1");
            LklOrder lklOrder = iLklOrderService.getOne(orderQueryWrapper);
            if (lklOrder != null){
                V3CcssCounterOrderCloseRequest req = new V3CcssCounterOrderCloseRequest();
                req.setOutOrderNo(outOrderNo);
                req.setMerchantNo(lklOrder.getMerchantNo());
                //req.setChannelId("2021052614391");

                //3. 发送请求
                String response = LKLSDK.httpPost(req);
                JSONObject jsonObject = JSONObject.parseObject(response);
                // 获取resp_data对象
                JSONObject respData = jsonObject.getJSONObject("resp_data");
                if (respData != null) {
                    String orderStatus = respData.getString("order_status");
                    if (orderStatus.equals("7")) {
                        return true;
                    }
                }
            }
        }catch (Exception e){
            return false;
        }
        return false;
    }
}
